﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YbPrintPlug
{
    internal static class Program
    {
        private static readonly string MutexName = "YB_PrintPlug";
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (Mutex mutex = new Mutex(true, MutexName, out bool createdNew))
            {
                if (createdNew)
                {
                    // 如果是第一次启动，则运行应用程序
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
                else
                {
                    // 如果已经有一个实例在运行，则提示用户
                    MessageBox.Show("程序已经在运行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 可选：激活已运行的实例窗口
                    ActivateExistingInstance();
                }
            }
        }
        private static void ActivateExistingInstance()
        {
            try
            {
                // 获取当前进程
                Process currentProcess = Process.GetCurrentProcess();

                // 查找其他同名进程
                foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    if (process.Id != currentProcess.Id)
                    {
                        // 激活窗口并将其带到前台
                        IntPtr handle = process.MainWindowHandle;
                        if (handle != IntPtr.Zero)
                        {
                            WinApi.ShowWindow(handle, WinApi.SW_RESTORE);
                            WinApi.SetForegroundWindow(handle);
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法激活现有实例：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
    // WinAPI 调用辅助类
    internal static class WinApi
    {
        public const int SW_RESTORE = 9;

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
    }
}
